package com.dj.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;

public class DESDecryptutil {

    private static final Logger logger = LoggerFactory.getLogger(DESDecryptutil.class);

    private static final String ALGORITHM = "DES"; // 加密算法名

    // 根据密码和keyGenerator生成密钥。
    public static SecretKey generateSecretKey(String key) {
        KeyGenerator keyGenerator = null;
        try {
            // Get the key generator
            keyGenerator = KeyGenerator.getInstance(ALGORITHM);
            // Instantiate an instance of SecureRandom
            // SecureRandom sr = new SecureRandom(key.getBytes());
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(key.getBytes());
            keyGenerator.init(sr);
            return keyGenerator.generateKey();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    // 根据密码加密字符串。
    public static String encryptStr(String data, String key) {
        byte[] bytes = data.getBytes();
        SecretKey secretKey = generateSecretKey(key);
        byte[] encryptBytes = encrypt(bytes, secretKey);
        return Base64.encodeBase64(encryptBytes);
    }

    // 根据密码加密字节数组。
    public static byte[] encrypt(byte[] bytes, String key) {
        SecretKey secretKey = generateSecretKey(key);
        return encrypt(bytes, secretKey);
    }

    private static byte[] encrypt(byte[] bytes, SecretKey secretKey) {
        byte[] encryptedObj = null;

        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM); // Get the cipher
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encryptedObj = cipher.doFinal(bytes);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return encryptedObj;
    }

    // 根据密码解密字符串。
    public static String decryptStr(String encryptedData, String key) {
        byte[] bytes = encryptedData.getBytes();
        SecretKey secretKey = generateSecretKey(key);
        return new String(decrypt(bytes, secretKey));
    }

    // 根据密码解密字节数组。
    public static String decrypt(String bytes, String key) {
        SecretKey secretKey = generateSecretKey(key);
        return new String(decrypt(Base64.decode(bytes), secretKey));
    }

    private static byte[] decrypt(byte[] bytes, SecretKey secretKey) {
        byte[] decryptedObj = null;

        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM); // Get the cipher
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            decryptedObj = cipher.doFinal(bytes);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return decryptedObj;
    }

}
